<?php
/*************************
  Coppermine Photo Gallery
  ************************
  Copyright (c) 2003-2014 Coppermine Dev Team
  v1.0 originally written by Gregory Demar

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License version 3
  as published by the Free Software Foundation.

  ********************************************
  Coppermine version: 1.5.30.1
**********************************************/

define('IN_COPPERMINE', true);
define('DB_INPUT_PHP', true);
define('DISPLAYIMAGE_PHP', true);
chdir('../../');
require_once 'include/init.inc.php';
require_once('androidcpg_enabled.php');
require_once 'include/picmgmt.inc.php';
require_once 'include/mailer.inc.php';
require_once 'include/smilies.inc.php';

/*known issue: code was edited to not count URL in comment character count. However
this resulted in the character count not being respected at all.

With the new code, the long urls don't affect the display of the hyperlinked word.
However, I can't figure out how to make the code respect the max comment word length and max comment length.
Formatted and unformatted words that are longer than the allowed setting do not get truncated. -Thu */

if (!$superCage->get->keyExists('event') && !$superCage->post->keyExists('event')) {
    cpg_die(CRITICAL_ERROR, $lang_errors['param_missing'], __FILE__, __LINE__);

    //Check if the form token is valid
} elseif ($superCage->post->keyExists('uploader') && $superCage->post->_getValue('uploader') == 'android'){

} elseif (!checkFormToken()) {
    cpg_die(ERROR, $lang_errors['invalid_form_token'], __FILE__, __LINE__);
}

if ($matches = $superCage->post->getMatched('event', '/^[a-z_]+$/')) {
    $event = $matches[0];
} elseif ($matches = $superCage->get->getMatched('event', '/^[a-z_]+$/')) {
    $event = $matches[0];
} else {
    $event = '';
}

switch ($event) {

case 'picture':

    if (!USER_CAN_UPLOAD_PICTURES && !USER_CAN_CREATE_ALBUMS) {
        if ($CONFIG['log_mode'] != 0) {
                log_write('Denied privileged access to db_input.php (upload picture) for user '.$USER_DATA['user_name'].' at ' . $hdr_ip, CPG_SECURITY_LOG);
        }
        cpg_die(ERROR, $lang_errors['perm_denied'], __FILE__, __LINE__);
    }

    $album = $superCage->post->getInt('album');
    $title = $superCage->post->getEscaped('title');
    $caption = $superCage->post->getEscaped('caption');
    $keywords = $superCage->post->getEscaped('keywords');
    $user1 = $superCage->post->getEscaped('user1');
    $user2 = $superCage->post->getEscaped('user2');
    $user3 = $superCage->post->getEscaped('user3');
    $user4 = $superCage->post->getEscaped('user4');

    // Check if the album id provided is valid
    if (!(GALLERY_ADMIN_MODE || user_is_allowed())) {

        $result = cpg_db_query("SELECT category FROM {$CONFIG['TABLE_ALBUMS']} WHERE aid = $album AND (owner = " . USER_ID . " OR category = " . (USER_ID + FIRST_USER_CAT) . (USER_CAN_UPLOAD_PICTURES  ? ' OR uploads = "YES"' : '') . ")");

        if (mysql_num_rows($result) == 0) {
            cpg_die(ERROR, $lang_db_input_php['unknown_album'], __FILE__, __LINE__);
        }

        $row = mysql_fetch_assoc($result);
        mysql_free_result($result);

        $category = $row['category'];

    } else {

        $result = cpg_db_query("SELECT category FROM {$CONFIG['TABLE_ALBUMS']} WHERE aid = $album");

        if (mysql_num_rows($result) == 0) {
            cpg_die(ERROR, $lang_db_input_php['unknown_album'], __FILE__, __LINE__);
        }

        $row = mysql_fetch_assoc($result);
        mysql_free_result($result);

        $category = $row['category'];
    }

    // Test if the filename of the temporary uploaded picture is empty
    // getRaw is safe here since this filename is generated by the server
    if ($superCage->files->getRaw("/userpicture/tmp_name") == '') {
        cpg_die(ERROR, $lang_db_input_php['no_pic_uploaded'], __FILE__, __LINE__);
    }

    // Pictures are moved in a directory named 10000 + USER_ID
    if (USER_ID && $CONFIG['silly_safe_mode'] != 1) {

        $filepath = $CONFIG['userpics'] . (USER_ID + FIRST_USER_CAT);
        $dest_dir = $CONFIG['fullpath'] . $filepath;

        if (!is_dir($dest_dir)) {

            mkdir($dest_dir, octdec($CONFIG['default_dir_mode']));

            if (!is_dir($dest_dir)) {
                cpg_die(CRITICAL_ERROR, sprintf($lang_db_input_php['err_mkdir'], $dest_dir), __FILE__, __LINE__, true);
            }

            chmod($dest_dir, octdec($CONFIG['default_dir_mode']));

            $fp = fopen($dest_dir . '/index.php', 'w');
            fwrite($fp, ' ');
            fclose($fp);
        }

        // Upload pictures in a sub-directory named according to the album ID
        if ($CONFIG['upload_create_album_directory']) {
            $filepath .= '/'.$album;
            $dest_dir .= '/'.$album;

            if (!is_dir($dest_dir)) {

                mkdir($dest_dir, octdec($CONFIG['default_dir_mode']));

                if (!is_dir($dest_dir)) {
                    cpg_die(CRITICAL_ERROR, sprintf($lang_db_input_php['err_mkdir'], $dest_dir), __FILE__, __LINE__, true);
                }

                chmod($dest_dir, octdec($CONFIG['default_dir_mode']));

                $fp = fopen($dest_dir . '/index.php', 'w');
                fwrite($fp, ' ');
                fclose($fp);
            }
        }

        $dest_dir .= '/';
        $filepath .= '/';

    } else {
        $filepath = $CONFIG['userpics'];
        $dest_dir = $CONFIG['fullpath'] . $filepath;
    }

    // Check that target dir is writable
    if (!is_writable($dest_dir)) {
        cpg_die(CRITICAL_ERROR, sprintf($lang_db_input_php['dest_dir_ro'], $dest_dir), __FILE__, __LINE__, true);
    }

    if (get_magic_quotes_gpc()) {
        //Using getRaw() as we have custom sanitization code below
        $picture_name = stripslashes($superCage->files->getRaw("/userpicture/name"));
    } else {
        $picture_name = $superCage->files->getRaw("/userpicture/name");
    }

    $picture_name = CPGPluginAPI::filter('upload_file_name', $picture_name);

    // Replace forbidden chars (including white spaces and special chars) with underscores
    $picture_name = replace_forbidden($picture_name);

    // Check that the file uploaded has a valid extension
    if (!preg_match("/(.+)\.(.*?)\Z/", $picture_name, $matches)) {
        $matches[1] = 'invalid_fname';
        $matches[2] = 'xxx';
    }

    if ($matches[2] == '' || !is_known_filetype($matches)) {
        cpg_die(ERROR, $lang_db_input_php['err_invalid_fext'] . ' ' . $CONFIG['allowed_file_extensions'], __FILE__, __LINE__);
    }

    // Create a unique name for the uploaded file
    $nr = 0;
    $picture_name = $matches[1] . '.' . $matches[2];

    while (file_exists($dest_dir . $picture_name)) {
        $picture_name = $matches[1] . '~' . $nr++ . '.' . $matches[2];
    }

    $uploaded_pic = $dest_dir . $picture_name;

    CPGPluginAPI::action('upload_html_pre_move', $superCage->files->getRaw("/userpicture/tmp_name"));

    // Move the picture into its final location
    // getRaw is safe here since this filename is generated by the server
    if (!move_uploaded_file($superCage->files->getRaw("/userpicture/tmp_name"), $uploaded_pic)) {
        cpg_die(CRITICAL_ERROR, sprintf($lang_db_input_php['err_move'], $picture_name, $dest_dir), __FILE__, __LINE__, true);
    }

    // Change file permission
    chmod($uploaded_pic, octdec($CONFIG['default_file_mode']));

    // Get picture information
    // Check that picture file size is lower than the maximum allowed
    if (filesize($uploaded_pic) > ($CONFIG['max_upl_size'] * 1024)) {

        @unlink($uploaded_pic);
        cpg_die(ERROR, sprintf($lang_db_input_php['err_imgsize_too_large'], $CONFIG['max_upl_size']), __FILE__, __LINE__);

    } elseif (is_image($picture_name)) {

        $imginfo = cpg_getimagesize($uploaded_pic);


        if ($imginfo == null) {

            // getimagesize does not recognize the file as a picture
            @unlink($uploaded_pic);
            cpg_die(ERROR, $lang_db_input_php['err_invalid_img'], __FILE__, __LINE__, true);

        } elseif ($imginfo[2] != GIS_JPG && $imginfo[2] != GIS_PNG && $CONFIG['GIF_support'] == 0) {

            // JPEG and PNG only are allowed with GD
            @unlink($uploaded_pic);
            cpg_die(ERROR, $lang_errors['gd_file_type_err'], __FILE__, __LINE__, true);

            // Check that picture size (in pixels) is lower than the maximum allowed
        } // Image is ok
    }

    // Upload is ok
    // Create thumbnail and internediate image and add the image into the DB
    $result = add_picture($album, $filepath, $picture_name, 0, $title, $caption, $keywords, $user1, $user2, $user3, $user4, $category, $raw_ip, $hdr_ip, $superCage->post->getInt('width'), $superCage->post->getInt('height'));

    if ($result !== true) {
        @unlink($uploaded_pic);
        cpg_die(CRITICAL_ERROR, isset($result['error']) ? $result['error'] : sprintf($lang_db_input_php['err_insert_pic'], $uploaded_pic) . '<br /><br />' . $ERROR, __FILE__, __LINE__, true);
    } elseif ($PIC_NEED_APPROVAL) {
        pageheader($lang_common['information']);
        msg_box($lang_common['information'], $lang_db_input_php['upload_success'], $lang_common['continue'], 'index.php');

        if ($CONFIG['upl_notify_admin_email']) {
            include_once('include/mailer.inc.php');
            cpg_mail('admin', sprintf($lang_db_input_php['notify_admin_email_subject'], $CONFIG['gallery_name']), make_clickable(sprintf($lang_db_input_php['notify_admin_email_body'], USER_NAME, $CONFIG['ecards_more_pic_target'].(substr($CONFIG["ecards_more_pic_target"], -1) == '/' ? '' : '/') .'editpics.php?mode=upload_approval')));
        }
        pagefooter();
    } else {
        if (cpg_pw_protected_album_access($CURRENT_PIC_DATA['aid']) === 1) {
            $redirect = "thumbnails.php?album=" . $CURRENT_PIC_DATA['aid'];
        } else {
            $redirect = "displayimage.php?pid=" . $CURRENT_PIC_DATA['pid'];
        }
        cpgRedirectPage($redirect, $lang_common['information'], $lang_db_input_php['upl_success'], 1,'success');
    }

    break;

    // Unknown event
default:
    if ($CONFIG['log_mode'] != 0) {
            log_write('Denied privileged access to db_input.php (unknown event) for user '.$USER_DATA['user_name'].' at ' . $hdr_ip, CPG_SECURITY_LOG);
    }
    cpg_die(CRITICAL_ERROR, $lang_errors['param_missing'], __FILE__, __LINE__);
}

?>